﻿<!-- wwwroot/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>SignalR 聊天</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding-top: 50px;
        }

        #messages {
            height: 400px;
            overflow-y: scroll;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="mt-5">SignalR 聊天</h1>
        <div id="messages"></div>
        <input type="text" id="userInput" class="form-control mt-2" placeholder="你的名字">
        <input type="text" id="messageInput" class="form-control mt-2" placeholder="输入消息...">
        <button id="sendButton" class="btn btn-primary mt-2">发送</button>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("http://localhost:5000/chatHub", { withCredentials: true }) // 允许发送凭证
            .configureLogging(signalR.LogLevel.Information)
            .build();

        // 启动连接
        connection.start().then(() => {
            console.log("SignalR 连接已建立");
        }).catch(err => console.error(err.toString()));

        // 接收消息
        connection.on("ReceiveMessage", (user, message) => {
            const msg = document.createElement("div");
            msg.textContent = `${user}: ${message}`;
            document.getElementById("messages").appendChild(msg);
            window.scrollTo(0, document.body.scrollHeight);
        });

        // 接收消息-在线人数
        connection.on("OnlineUsers", (user, message) => {
            const msg = document.createElement("div");
            msg.textContent = `${user}: ${message}`;
            document.getElementById("messages").appendChild(msg);
            window.scrollTo(0, document.body.scrollHeight);
        });

        // 发送消息
        document.getElementById("sendButton").addEventListener("click", async () => {
            const user = document.getElementById("userInput").value;
            const message = document.getElementById("messageInput").value;
            await connection.invoke("SendMessage", user, message);
            document.getElementById("messageInput").value = "";
        });
    </script>
</body>
</html>